<?php
namespace app\client\lib;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\lib\Redis;

class SMS {
    
    const AccessKeyId = 'LTAIoLK1RamE6JP2';
    const AccessSecret = 'em9eNzuYhy9wZnkPocL8vs76fek1K6';
    
    private $redis = null;
    private $mobile = null;
    private $mobileCountKey = '';
    private $mobileCount = 0;
    
    private $time = 0;
    private $today = 0;
    
    public function __construct($mobile, $ip = '') {
        $time = time();
        $today = date('Y-m-d', $time);
        
        $this->today = strtotime($today);
        $this->time = time();
        $this->mobile = $mobile;
        $this->mobileCountKey = 'sms_' . $this->mobile . '_count';
        $this->redis = new Redis();
        
        $this->mobileCount = $this->redis->get($this->mobileCountKey, 0);
    }
    
    public function send($key, $code, $signName, $templateCode, array $templateParam, $interval = 60, $expire = 5) {
        
        $expire = $expire * 60;
        
        
        $sendRes = ['success' => false, 'msg' => '发送验证码失败', 'debug' => ''];

        /* if($this->redis->handler()->ttl($key) > ($expire - 60)) {
            $sendRes['msg'] = '验证码已发送';
            return $sendRes;
        } */
        
        
        
        try {
            
            AlibabaCloud::accessKeyClient(self::AccessKeyId, self::AccessSecret)
            ->regionId('cn-shenzhen')
            ->asDefaultClient();
            
            $result = AlibabaCloud::rpc()
            ->product('Dysmsapi')
            ->scheme('https')
            ->version('2017-05-25')
            ->action('SendSms')
            ->method('POST')
            ->host('dysmsapi.aliyuncs.com')
            ->options([
                'query' => [
                    'RegionId' => "cn-hangzhou",
                    'PhoneNumbers' => $this->mobile,
                    'SignName' => $signName,
                    'TemplateCode' => $templateCode,
                    'TemplateParam' => json_encode($templateParam)
                ],
            ])
            ->request()->toArray();
            
            if($result['Code'] === 'OK') {
                $sendRes['success'] = true;
                $sendRes['msg'] = '发送验证码成功';
                
                $nextDay = strtotime('+1 day', $this->today);
                
                if($this->mobileCount <= 0) {
                    $this->redis->setex($this->mobileCountKey, 1, $nextDay - $this->time);
                }else {
                    $this->redis->handler()->incr($this->mobileCountKey);
                }
                
                $this->redis->setex($key, ['code' => $code, 'mobile' => $this->mobile], $expire);
                
            }else {
                $sendRes['debug'] = $result['Message'];
            }
            
            
        } catch (ClientException $e) {
            $sendRes['debug'] = $e->getErrorMessage();
        } catch (ServerException $e) {
            $sendRes['debug'] = $e->getErrorMessage();
        }
        
        return $sendRes;
    }
    
    public function count() { //发送的次数
        return $this->mobileCount;
    }
    
    public function createCode($len=4){
        $str = str_shuffle('0123456789');
        $max = strlen($str) - 1;
        $code = '';
        for($i=0; $i<$len; $i++){
            $index = mt_rand(0, $max);
            $code .= substr($str,$index,1);
        }
        return $code;
    }
    
    
    public function validate($key, $code) {
        $res = $this->redis->get($key, '');
        if($res === '') {
            return false;
        }
        
        $res = json_decode($res, true);
        if(empty($res)) {
            return false;
        }
        
        if($res['mobile'] != $this->mobile || $res['code'] != $code) {
            return false;
        }
        
        return true;
    }
    
    public function end() {
        $this->redis->close();
        $this->redis = null;
    }
    
}



